<?php


namespace app\common\lib;


use app\common\exception\ApiErrDesc;
use app\common\traits\SmsTrait;
use app\Request;
use catcher\exceptions\CatchException;
use catcher\exceptions\ValidateFailedException;
use Curl\Curl;
use think\exception\HttpException;
use think\facade\Log;

class Sms
{
    use SmsTrait;

    private $requestUrl;
    private static $instance = null;
    private array $smsConfig;

    public static function getInstance(): ?Sms
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    final private function __construct()
    {
        $this->smsConfig = $this->getSmsConfig();
    }

    private function setRequestUrl(string $actionName = ''): void
    {
        $this->requestUrl = sprintf("%s?action=%s", $this->smsConfig["requestUrl"], $actionName);
    }

    private function getRequestUrl()
    {
        return $this->requestUrl;
    }


    private function getCommonParams(): array
    {
        return [
            'userid' => $this->smsConfig["userid"],
            'password' => $this->smsConfig["password"],
            'account' => $this->smsConfig["account"],
        ];
    }

    /**
     * 批量发送短信
     * @param array $telephoneArr
     * @param string $content
     */
    public function sendMessage(array $telephoneArr, string $content)
    {
        $this->setRequestUrl('send');
        $params = $this->getCommonParams();
        //$params["mobile"] = implode(",", $telephoneArr);
        $params["mobile"] = "18088666140";
        $params["content"] = $content;
        $params["action"] = "send";

        //$result = (new Curl())->post($this->getRequestUrl(), $params);
        //return (array)simplexml_load_string($result->getResponse());
        return [
            'returnstatus' => "Success",
            'message' => "ok",
            'remainpoint' => "42562",
            "taskID" => "19704416",
            "successCounts" => count($telephoneArr)
        ];
    }

    public function checkMessageContent(string $content)
    {
        try {
            $this->setRequestUrl('checkkeyword');
            $pattern = '/(\@.*@)/U';
            preg_match_all($pattern, $content, $match);
            if (!empty($match[0])) {
                $content = str_replace($match[0], "", $content);
            }
            $param = $this->getCommonParams();
            $param["content"] = $content;
            $result = (new Curl())->post($this->getRequestUrl(), $param);
            return (array)simplexml_load_string($result->getResponse());
        } catch (\Exception $exception) {
            $errorMessage = sprintf("短信模板检测失败:原始内容:%s,返回结果:%s", $content, $exception->getMessage());
            Log::error($errorMessage);
            throw new ValidateFailedException($errorMessage);
        }
    }

    public function getBalance(): array
    {
        try {
            $this->setRequestUrl("overage");
            $param = $this->getCommonParams();

            $result = (new Curl())->post($this->getRequestUrl(), $param);
            return (array)simplexml_load_string($result->getResponse());
        } catch (\Exception $exception) {
            $errorMessage = sprintf("短信余额调用失败%s", $exception->getMessage());
            Log::error($errorMessage);
            throw new ValidateFailedException($errorMessage);
        }
    }


    final public function __clone()
    {
        // TODO: Implement __clone() method.
    }
}